import { useState, useEffect, HTMLAttributes, memo } from "react"
import styled from "@emotion/styled"
import { toast } from "react-toastify"

type Props = HTMLAttributes<HTMLDivElement> & {
    sendCode: () => Promise<{ success: boolean }>
}

// 可以改为父组件的 isCounting/ setIsCounting 控制
// type Props {
//   isCounting: boolean;
//   setIsCounting: (value: boolean) => void;
//   onSend: () => void;
// }

const CodeCountdownTimer = memo(({ sendCode, className = "" }: Props) => {
    const _timer = 60
    const [countdown, setCountdown] = useState(_timer)
    const [isCounting, setIsCounting] = useState(true)
    // 倒计时逻辑
    useEffect(() => {
        let timer: number | undefined | NodeJS.Timeout
        if (isCounting && countdown > 0) {
            timer = setInterval(() => {
                setCountdown((prev) => prev - 1)
            }, 1000)
        } else if (countdown === 0) {
            setIsCounting(false)
            // setCountdown(60);
        }
        return () => clearInterval(timer)
    }, [isCounting, countdown])

    // 发送验证码
    const handleSendCode = async () => {
        //倒计时结束才能再次发送
        if (!isCounting) {
            try {
                const res = await sendCode() // 调用父组件的SendCode方法
                if (res) {
                    setCountdown(_timer)
                    setIsCounting(true)
                }
            } catch (error) {
                console.error("send failed:", error)
                toast("failed to send SMS")
            }
        }
    }

    return (
        <CountdownBox
            onClick={handleSendCode}
            className={`${isCounting ? "disabled" : ""} ${className}`}
        >
            {isCounting ? (
                <CountdownP>
                    Resend code <Countdown>{countdown}</Countdown>
                </CountdownP>
            ) : (
                <CountdownP>Send code</CountdownP>
            )}
        </CountdownBox>
    )
})

export default CodeCountdownTimer

const CountdownBox = styled.div`
    cursor: pointer;
    transition: all 0.3s ease;
    &:not(.disabled) p {
        color: #0f0f10;
    }
`

const CountdownP = styled.p`
    margin: 0;
    font-family: "Gilroy";
    font-weight: 400;
    font-size: 14rem;
    line-height: 20rem;
    letter-spacing: 0;
    text-align: right;
    color: #a2a3a5;
`

const Countdown = styled.span`
    margin: 0 2rem;
    font-family: "Gilroy";
    font-weight: 400;
    font-size: 14rem;
    line-height: 20rem;
    letter-spacing: 0;
    text-align: right;
    color: #0f0f10;
`
